import _ from 'lodash';
import { dist, scatterPointLayerColors, polygonLayerColors, pngs } from './helper.js';
import emitter from '#/utils/events';
let Map = null;
try {
  Map = AMap?.Map;
} catch (e) {
  // console.log(Map)
}
const heatLayer = 'heatLayer',
  linkLayer = 'linkLayer',
  polymerization = 'polymerization',
  scatterPointLayer = 'scatterPointLayer',
  gridLayer = 'gridLayer',
  districtLayer = 'districtLayer',
  contourLayer = 'contourLayer',
  labelsLayer = 'labelsLayer',
  polygonLayer = 'polygonLayer',
  hexagonLayer = 'hexagonLayer',
  iconLayer = 'iconLayer',
  markersAttribute = 'markersAttribute',
  districtLayerCountry = 'districtLayerCountry',
  polygon = 'polygon',
  districtSearch = 'districtSearch',
  fitPolygonView = 'fitPolygonView';

let polygonLayerIdx = 0,
  district = null,
  polygons = [];

class VisualMap {
  constructor() {
    this.markerClick = false;
    this.markerDomObj = {}; // 存储每一个点标记节点
    this.markerDataObj = {}; // 存储每一个点标记数据
    this.overMarkerId = ''; // 当前展示的信息窗体id
    this.staticProps = {};
    this.markerClickTime = null;
    this.AMapAttribute = {
      resizeEnable: true, // 是否监听缩放
      mapStyle: 'amap://styles/grey', // 地图样式
      zoom: 3, // 设置地图显示的缩放级别
      viewMode: '3D',
      pitchEnable: false, // 是否允许倾斜
      lang: 'zh_cn', // 设置地图语言类型
      zooms: [3, 18], // 地图显示的缩放级别范围3-18
      expandZoomRange: true, // 配合zooms，最大到20
      center: [104.5525, 32.0227], // 设置中国展示地图中心
      isHotspot: true, // 是否开启地图热点和标注的hover效果
      rotation: 0, // 地图顺时针旋转角度 0-360
      rotateEnable: false, // 地图是否可旋转
      dragEnable: true, // 是否可通过鼠标拖拽平移
      zoomEnable: true, // 是否可缩放
      doubleClickZoom: false, // 是否可通过双击鼠标放大地图
      keyboardEnable: true, // 是否可通过键盘控制
      scrollWheel: true, // 是否可通过滚轮控制
      opacity: 0.1,
      features: ['bg', 'road', 'building', 'point'], // bg(地图背景) point(POI点) road(道路) building(建筑物)
    }; // 地图配置
    this.subComponentsOptions = {
      heatLayer: {
        style: {
          radius: 16,
          color: {
            0.5: '#2c7bb6',
            0.65: '#abd9e9',
            0.7: '#ffffbf',
            0.9: '#fde468',
            1.0: '#d7191c',
          },
        },
      },
      linkLayer: {
        blendMode: 'lighter',
        style: {
          // 曲率 [-1, 1] 区间
          curveness: function (data) {
            if (data.value.dis < 100) {
              return 0.07;
            } else if (data.value.dis < 300) {
              return 0.05;
            } else if (data.value.dis < 500) {
              return 0.02;
            } else if (data.value.dis < 700) {
              return 0.01;
            } else {
              return 0.005;
            }
          },
          opacity: 0.8,
          color: '#5DFBF9',
        },
      },
      polymerization: {
        gridSize: 40,
        minClusterSize: 2,
      },
      scatterPointLayer: {
        unit: 'px',
        style: {
          // 根据车辆类型设定不同半径
          radius: function (obj) {
            const value = obj.value;
            switch (parseInt(value.type)) {
              case 3:
                return 3;
              case 4:
                return 3;
              case 41:
                return 3;
              case 5:
                return 3;
              default:
                return 3;
            }
          },
          height: 0,
          // 根据车辆类型设定不同填充颜色
          color: function (obj) {
            const value = obj.value;
            switch (parseInt(value.type)) {
              case 3:
                return scatterPointLayerColors[0];
              case 4:
                return scatterPointLayerColors[1];
              case 41:
                return scatterPointLayerColors[2];
              case 5:
                return scatterPointLayerColors[3];
              default:
                return scatterPointLayerColors[4];
            }
          },
          opacity: 1,
        },
      },
      gridLayer: {
        unit: 'meter',
        mode: 'count',
        style: {
          color: ['#0868AC', '#43A2CA', '#43A2CA', '#7BCCC4', '#BAE4BC', '#F0F9E8', '#F0F9E8'],
          radius: 600,
          opacity: 0.9,
          gap: 150,
          height: [0, 0],
        },
      },
      districtLayer: {
        mode: 'count',
        style: {
          color: ['#0c2c84', '#225ea8', '#225ea8', '#41b6c4', '#7fcdbb', '#c7e9b4', '#ffffcc'],
          height: [0, 300000],
          opacity: 0.86,
          borderWidth: 1,
          borderColor: '#ffffff',
        },
      },
      contourLayer: {
        // interpolation: 数据插值设置项，可缺省
        interpolation: {
          // step: {number}, 用于数据插值的步长，可缺省，缺省值为 500
          // step 不宜过小，过小的 step 可能会导致绘制性能严重下降
          step: 300,
          // effectRadius: {number}, 每一个原始值在插值过程中影响的范围，可缺省，缺省值为 1000
          // effectRadius / step 的值不宜过大，建议在 20 以内，可以获得良好的性能效果
          effectRadius: 800,
        },
        // threshold: {number}, 等高线拆分步长，及按照用户提供的数据每隔 threshold 大小来绘制一条等高线
        // 可缺省，缺省值为 1
        threshold: 3,
        // smoothNumber: {number}, 等高线平滑次数，可缺省，缺省值为 2
        smoothNumber: 3,
        // style: 等高线绘制样式，可缺省
        style: {
          // height: {number}, 3D 等高线最大高度, 可缺省，缺省值为 5 * 1E4
          height: 5 * 1e4,
          // color: {Array}, 绘制等高线使用的颜色序列, 可缺省，缺省值为 ["#3656CD", "#655FE7", '#20C2E1', '#23D561', '#9CD523', '#F1E229', '#FFBF3A', '#FB8C00', '#FF5252', "#BC54E2", "#FF6FCE"]
          color: [
            'rgba(7,49,117,0.5)',
            'rgba(4,71,138,0.5)',
            'rgba(0,109,176,0.5)',
            'rgba(6,152,196,0.5)',
            'rgba(65,182,196,0.5)',
            'rgba(127,205,187,0.2)',
            'rgba(199,233,180,0.2)',
          ],
        },
      },
      labelsLayer: {
        style: {
          direction: 'center',
          offset: [0, 0],
          text: function (data) {
            return '￥' + parseInt(data.value['2018年']);
          },
          fillColor: function (data) {
            const income = +data.value['2018年'];
            return income < 20000 ? '#0C6DB0' : income < 50000 ? '#2DABBA' : '#82CF9C';
          },
          fontSize: function (data) {
            const income = +data.value['2018年'];
            return income < 20000
              ? 12
              : income < 30000
              ? 16
              : income < 40000
              ? 20
              : income < 50000
              ? 24
              : income < 60000
              ? 28
              : 32;
          },
          strokeColor: '#000',
          strokeWidth: 0,
          opacity: 1,
        },
        selectStyle: {
          fontSize: function (data) {
            const income = +data.value['2018年'];
            return income < 20000
              ? 12
              : income < 30000
              ? 16
              : income < 40000
              ? 20
              : income < 50000
              ? 24
              : income < 60000
              ? 28
              : 32;
          },
          strokeColor: '#000',
          strokeWidth: 1,
        },
      },
      polygonLayer: {
        style: {
          height: function () {
            return Math.random() * 20000;
          },
          opacity: 0.8,
          color: function () {
            return polygonLayerColors[polygonLayerIdx++ % polygonLayerColors.length];
          },
        },
      },
      hexagonLayer: {
        unit: 'meter',
        mode: 'count',
        style: {
          color: ['#0868AC', '#43A2CA', '#43A2CA', '#7BCCC4', '#BAE4BC', '#F0F9E8', '#F0F9E8'],
          radius: 600,
          opacity: 0.9,
          gap: 150,
          height: [0, 0],
        },
      },
      iconLayer: {
        source: function (res) {
          let i = res.index;
          return '//a.amap.com/Loca/static/manual/weathers/' + pngs[i % pngs.length] + '.png';
        },
        style: {
          size: 28,
        },
      },
      districtSearch: {},
      districtLayerCountry: {
        styles: {
          'nation-stroke': '#2e84ce',
          'coastline-stroke': '',
          'province-stroke': '#2e84ce',
          'city-stroke': '', //中国特有字段
          fill: '#0058BF',
        },
      },
    }; // 子组件配置
    this.visualMap = null; // 地图实例
    this.subComponents = []; // 子组件 heatLayer(热力)  linkLayer(飞线)  polymerization(点聚合)  scatterPointLayer(散点)  gridLayer(网隔热力)  districtLayer(区域热力)  hexagonLayer(蜂窝热力)  contourLayer(等值面)  labelsLayer(文字)  labelsLayer(行政区面)  iconLayer(天气预报)
    this.heatLayer = null;
    this.linkLayer = null;
    this.polymerization = null;
    this.scatterPointLayer = null;
    this.gridLayer = null;
    this.districtLayer = null;
    this.contourLayer = null;
    this.labelsLayer = null;
    this.polygonLayer = null;
    this.hexagonLayer = null;
    this.iconLayer = null;
    this.districtSearch = null;
    this.markersAttribut = null;
    this.districtLayerCountry = null;
    this.polygon = null;
    this.fitPolygonView = null;
  }
}

// 初始化地图
VisualMap.prototype.onLoad = function (callback) {
  if (Map) {
    this.visualMap = new Map('visualMap', {
      ...(this.AMapAttribute || {}),
      ...(this.staticProps?.AMapAttribute || {}),
      style: {
        borderWidth: 1,
        borderColor: '#ffffff',
      },
    });
    if (this.staticProps?.subComponents?.length) {
      this.setSubComponents();
    }
    if (this.visualMap) {
      this.visualMap?.on('click', (ev) => callback && callback(ev));
      this.visualMap.on('zoomchange', () => {
        this.visualMap?.clearInfoWindow();
        emitter.emit('visualMapData', {
          center: this.visualMap?.getCenter(),
          bounds: this.visualMap?.getBounds(),
          zoom: this.visualMap?.getZoom(),
        });
      });
      this.visualMap.on('dragging', () => {
        this.visualMap?.clearInfoWindow();
        emitter.emit('visualMapData', {
          center: this.visualMap?.getCenter(),
          bounds: this.visualMap?.getBounds(),
        });
      });
    }
    return this.visualMap;
  }
  return null;
};

// 主要用来修改初始化地图配置
VisualMap.prototype.setDefaultVisualMapData = function (props = {}) {
  this.staticProps = { ...(props || {}) };
  // 修改地图缩放比例
  const dom = document.querySelector('#visualMap'),
    zoom = ((dom.offsetHeight * dom.offsetWidth) / (835 * 412)) * (props.multiple || 0.26) + 3;
  if (props.zoom) {
    this.AMapAttribute.zoom = props?.zoom;
    this.AMapAttribute.zooms = [props?.zoom, 18];
  } else {
    this.AMapAttribute.zoom = zoom;
    this.AMapAttribute.zooms = [zoom, 18];
  }

  this.subComponents = this.staticProps?.subComponents || [];
};

// 添加子组件
VisualMap.prototype.setSubComponents = function () {
  if (!this.staticProps?.subComponents?.length) return;
  const list = [
    heatLayer,
    linkLayer,
    scatterPointLayer,
    gridLayer,
    districtLayer,
    contourLayer,
    labelsLayer,
    polygonLayer,
    hexagonLayer,
    iconLayer,
    markersAttribute,
  ];
  _.forEach(this.staticProps?.subComponents || [], (_s) => {
    switch (_s?.name) {
      case heatLayer:
        this.setHeatLayer(_s);
        break;
      case linkLayer:
        this.setLinkLayer(_s);
        break;
      case polymerization:
        this.setPolymerization(_s);
        break;
      case scatterPointLayer:
        this.setScatterPointLayer(_s);
        break;
      case gridLayer:
        this.setGridLayer(_s);
        break;
      case districtLayer:
        this.setDistrictLayer(_s);
        break;
      case contourLayer:
        this.setContourLayer(_s);
        break;
      case labelsLayer:
        this.setLabelsLayer(_s);
        break;
      case polygonLayer:
        this.setPolygonLayer(_s);
        break;
      case hexagonLayer:
        this.setHexagonLayer(_s);
        break;
      case iconLayer:
        this.setIconLayer(_s);
        break;
      case districtSearch:
        this.setDistrictSearch(_s);
        break;
      case markersAttribute:
        this.setMarkersAttribute(_s);
        break;
      case districtLayerCountry:
        this.setDistrictLayerCountry(_s);
        break;
      case polygon:
        this.setPolygon(_s);
        break;
      case fitPolygonView:
        this.setFitViewFun(_s);
        break;
      default:
        break;
    }
    if (list.includes(_s?.name)) {
      this[_s?.name]?.setOptions({
        ...(this.subComponentsOptions[_s?.name] || {}),
        ...(_s?.options || {}),
      });
      this[_s?.name]?.render();
    }
  });
};

// 简易行政区
VisualMap.prototype.getColorByDGP = (colorArr = [], slide = {}, defaultColor = '') => {
  return (
    colorArr.filter((_c) => slide?.num >= _c?.min && slide?.num < _c?.max)[0]?.color || defaultColor
  );
};
VisualMap.prototype.setDistrictLayerCountry = function (slide = {}) {
  this.districtLayerCountry = new AMap.DistrictLayer.Country({
    zIndex: 11,
    SOC: 'CHN',
    depth: 1,
    ...(this.subComponentsOptions[slide?.name] || {}),
    styles: {
      ...(this.subComponentsOptions[slide?.name]?.styles || {}),
      ...(slide?.options?.styles || {}),
      fill: (props) => {
        //中国特有字段
        return this.getColorByDGP(
          slide?.data?.adcodeColor || [],
          slide?.data?.adcodeObj[props?.adcode_pro] || {},
          slide?.defaultColor || '',
        );
      },
    },
  });

  this.visualMap.setLayers(
    !slide?.isBasics
      ? [
          new AMap.DistrictLayer.World({
            zIndex: 10,
            styles: {
              'nation-stroke': function (props) {
                if (props.type === 'Nation_Border_China') {
                  return 'transparent';
                } else {
                  return '#181718';
                }
              },
              'coastline-stroke': '',
              fill: '#181718',
            },
          }),
          this.districtLayerCountry,
        ]
      : [this.districtLayerCountry],
  );
};

// 自定义点标记
VisualMap.prototype.setMarkersAttribute = function (slide = {}) {
  this.markersAttribut && this.markersAttribut?.clear();
  this.visualMap?.remove(Object.values(this.markerDomObj || {}));
  this.markersAttribut = new AMap.LabelsLayer({
    zIndex: 1000,
    collision: false,
    animation: true,
  });
  this.visualMap && this.visualMap?.clearInfoWindow();
  this._setMarkersAttribute(slide);
};
// 设置标记点属性
VisualMap.prototype._setMarkersAttribute = function (slide = {}) {
  this.markerDomObj = {};
  this.markerDataObj = {};
  let positionList = [];

  // let geocoder = new AMap.Geocoder({
  //   city: "010", //城市设为北京，默认：“全国”
  //   radius: 1000 //范围，默认：500
  // });
  _.forEach(slide?.data || [], (_d) => {
    let lng = _d?.longitude || '0',
      lat = _d?.latitude || '0',
      lnglat = [lng, lat];
    // geocoder.getAddress(lnglat, function(status, result) {
    //   console.log(_d?.deptNum, _d?.deptName, result.regeocode.addressComponent.adcode) // 别删
    // });
    if (_d?.assetType === 'G') positionList.push(lnglat);
    let marker = new AMap.Marker({
      map: this.visualMap,
      position: lnglat,
      offset: new AMap.Pixel(-15, -15),
      zIndex: -100,
      extData: {
        id: _d?.assetNum || '', // 当前数据
      },
      content: slide?.render && slide?.render(_d, slide?.option || {}),
    });
    const code = slide?.option?.code ? _d[slide?.option?.code] : _d?.deptNum;
    this.markerDomObj[code] = marker;
    this.markerDataObj[code] = _d;
    AMap.event.addListener(marker, 'mouseover', () => {
      this._setInfo(marker, slide, _d);
      this.overMarkerId = code;
    });
    AMap.event.addListener(marker, 'click', () => {
      this.markerClickTime = setTimeout(() => {
        if (this.markerClick) {
          this.markerClick = false;
          clearTimeout(this.markerClickTime);
          return;
        }
        slide.pushAllAsset && slide.pushAllAsset(_d);
      }, 200);
    });
    AMap.event.addListener(marker, 'dblclick', () => {
      this.markerClick = true;
      slide.dblclick && slide.dblclick(_d);
    });
    AMap.event.addListener(marker, 'mouseout', () => {
      this.visualMap && this.visualMap?.clearInfoWindow();
      this.overMarkerId = '';
    });
  });
  if (slide?.option?.isFitView) {
    this.setFitViewFun({}, positionList);
  }
};

// 设置可视区域
VisualMap.prototype.setFitViewFun = function (slide = {}, list = []) {
  this.fitPolygonView && this.fitPolygonView?.hide();
  let positions = [];
  if (list?.length) positions = list;
  else
    Object.values(this.markerDataObj || {})?.forEach((m) =>
      positions.push([m?.longitude || '0', m?.latitude || '0']),
    );

  this.fitPolygonView = new AMap.Polygon({
    path: positions, //以点的坐标创建一个隐藏的多边形
    map: this.visualMap,
    strokeOpacity: 0, //透明
    fillOpacity: 0, //透明
    bubble: true, //事件穿透到地图
    ...(slide?.option || {}),
  });

  if (slide?.change?.dragging) {
    this.fitPolygonView.on('dragging', (e) => {
      slide.sendLnglat && slide.sendLnglat(e.lnglat, true);
    });
  }
  if (slide?.change?.click) {
    this.visualMap &&
      this.visualMap.on('click', (e) => {
        let lng = e.lnglat.getLng(),
          lat = e.lnglat.getLat();
        slide?.sendLnglat({
          lng,
          lat,
        });
      });
  }

  if (this.visualMap) {
    this.visualMap?.add(this.fitPolygonView);
    // 缩放地图到合适的视野级别
    this.visualMap?.setFitView([this.fitPolygonView]);
    emitter.emit('visualMapData', {
      center: this.visualMap?.getCenter(),
      bounds: this.visualMap?.getBounds(),
      initZoom: this.visualMap?.getZoom(),
    });
  }
};

// 信息窗体
VisualMap.prototype._setInfo = function (marker, slide = {}, obj) {
  this.makerInfoWindow = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    anchor: 'top-left',
    content: slide?.maskInfoRender && slide?.maskInfoRender(obj, slide?.option || {}),
  });
  this.makerInfoWindow.open(this.visualMap, marker?.getPosition());
};

// 更新点标记
VisualMap.prototype.upDataMarkersAttribute = function (slide = {}) {
  Object.keys(this.markerDomObj || {})?.forEach((m) => {
    const markerSlide = this.markerDomObj[m] || null,
      markerDataSlide = this.markerDataObj[m] || {};
    markerSlide?.setContent(slide?.render && slide?.render(markerDataSlide, slide?.option || {}));
  });
  this.makerInfoWindow &&
    this.makerInfoWindow?.setContent(
      slide?.maskInfoRender &&
        slide?.maskInfoRender({ assetNum: this.overMarkerId }, slide?.option || {}),
    );
};
// 更新点标记 TODO
VisualMap.prototype.upDateMarker = function ({ list = [], renderMarker, renderInfo }) {
  _.forEach(list || [], (_l) => {
    if (this.overMarkerId === _l?.deptNum) {
      this.makerInfoWindow && this.makerInfoWindow?.setContent(renderInfo(_l));
    }
    if (_l?.isUpdateMarker) {
      let markerSlide = this.markerDomObj.get(_l?.deptNum);
      markerSlide.setContent(renderMarker(_l));
      this.markerDomObj.set(_l?.deptNum, markerSlide);
    }
  });
};

// 覆盖物
VisualMap.prototype.setPolygon = function (slide = {}) {
  // 创建面覆盖物
  this.polygon = new AMap.Marker({
    position: [126.39, 22.5],
    content: slide?.render && slide?.render(),
  });
  this.visualMap.add(this.polygon);
};

// 点热力
VisualMap.prototype.setHeatLayer = function (slide = {}) {
  this.heatLayer = new Loca.HeatmapLayer({
    map: this.visualMap,
  });
  this.heatLayer.setData(slide?.data || [], {
    lnglat: 'coordinate',
    value: 'count',
  });
};

// 网格热力
VisualMap.prototype.setGridLayer = function (slide = {}) {
  this.gridLayer = new Loca.GridLayer({
    map: this.visualMap,
  });
  this.gridLayer.setData(slide?.data || '', {
    lnglat: function (obj) {
      let val = obj.value;
      return [val.lng, val.lat];
    },
    value: 'count',
    type: 'tsv',
  });
};

// 蜂窝热力
VisualMap.prototype.setHexagonLayer = function (slide = {}) {
  this.hexagonLayer = new Loca.HexagonLayer({
    map: this.visualMap,
  });
  this.hexagonLayer.setData(slide?.data || '', {
    lnglat: function (obj) {
      let val = obj.value;
      return [val.lng, val.lat];
    },
    value: 'count',
    type: 'tsv',
  });
};

// 区域热力
VisualMap.prototype.setDistrictLayer = function (slide = {}) {
  this.districtLayer = new Loca.DistrictLayer({
    map: this.visualMap,
    // fitView: true
  });
  this.districtLayer.setData(slide?.data || '', {
    type: 'csv',
    lnglat: '经纬度',
    value: '知名景区数量',
  });
  // if(slide?.isAddBaseMap) this.districtLayer.setMap(this.visualMap);
};

// 飞线
VisualMap.prototype.setLinkLayer = function (slide = {}) {
  this.linkLayer = new Loca.LinkLayer({
    map: this.visualMap,
    fitView: false,
  });
  this.linkLayer.setData(slide?.data?.slice(0, 500) || '', {
    lnglat: 'lnglat',
  });
};

// 散点
VisualMap.prototype.setScatterPointLayer = function (slide = {}) {
  this.scatterPointLayer = new Loca.ScatterPointLayer({
    map: this.visualMap,
    fitView: false,
  });
  this.scatterPointLayer.setData(slide?.data?.slice(0, 10000) || '', {
    lnglat: function (obj) {
      let value = obj.value;
      return [value.lng, value.lat];
    },
    type: 'csv',
  });
};

// 等值面
VisualMap.prototype.setContourLayer = function (slide = {}) {
  this.contourLayer = new Loca.ContourLayer({
    // shape: {string}, 等高线类型 'isoband'为等高面, 'isoline'为等高线, 必填
    shape: 'isoband',
    map: this.visualMap,
  });
  this.contourLayer.setData(slide?.data || [], {
    // lnglat: {string}, 数据中经纬度坐标所在的列名称, 必填
    lnglat: 'lnglat',
    // value: {string}, 数据中权重数据所在的列名称, 必填
    value: 'count',
  });
};

// 文字
VisualMap.prototype.setLabelsLayer = function (slide = {}) {
  this.labelsLayer = new Loca.LabelsLayer({
    map: this.visualMap,
  });
  this.labelsLayer.setData(slide?.data || [], {
    type: 'csv',
    lnglat: function (o) {
      return dist[o.value['地区']];
    },
  });
};

// 行政区面
VisualMap.prototype.setPolygonLayer = function (slide = {}) {
  this.polygonLayer = new Loca.PolygonLayer({
    map: this.visualMap,
  });
  this.polygonLayer.setData(slide?.data || [], {
    lnglat: 'coordinates',
  });
};

// 天气预报
VisualMap.prototype.setIconLayer = function (slide = {}) {
  this.iconLayer = new Loca.IconLayer({
    map: this.visualMap,
  });
  this.iconLayer.setData(slide?.data || [], {
    lnglat: 'center',
  });
};

// 行政区边界
VisualMap.prototype.setDistrictSearch = function (slide = {}) {
  // 加载行政区划插件
  if (!district) {
    // 实例化DistrictSearch
    const opts = {
      subdistrict: 0, // 获取边界不需要返回下级行政区
      extensions: 'all', // 返回行政区边界坐标组等具体信息
      level: 'district', // 查询行政级别为 市
    };
    district = new AMap.DistrictSearch(opts);
  }
  district.search(slide?.data || '中国', (status, result) => {
    this.visualMap.remove(polygons); // 清除上次结果
    polygons = [];
    const bounds = result?.districtList[0]?.boundaries || '';
    if (bounds) {
      for (let i = 0, l = bounds.length; i < l; i++) {
        //生成行政区划polygon
        const polygon1 = new AMap.Polygon({
          strokeWeight: 1,
          path: bounds[i],
          fillOpacity: 0.4,
          fillColor: '',
          strokeColor: '#1684ce',
        });
        polygons.push(polygon1);
      }
    }
    this.visualMap.add(polygons);
    this.visualMap.setFitView(polygons); // 视口自适应
  });
};

// 点聚合
VisualMap.prototype.setPolymerization = function (slide = {}) {
  if (this.polymerization) {
    this.polymerization?.setMap(null);
  }
  this.polymerization = new AMap.MarkerClusterer(
    this.visualMap,
    Object.values(this.markerDomObj || {}),
    {
      ...(this.subComponentsOptions[slide?.name] || {}),
      ...(slide?.options || {}),
      renderClusterMarker: (e) =>
        e.marker.setContent(slide.render && slide.render(e, slide?.option || {})),
    },
  );
};

// 卸载
VisualMap.prototype.destroy = function () {
  if (this.visualMap) {
    this.visualMap?.destroy();
  }
  clearTimeout(this.markerClickTime);
  this.markerDomObj = {}; // 存储每一个点标记节点
  this.markerDataObj = {}; // 存储每一个点标记数据
  this.overMarkerId = ''; // 当前展示的信息窗体id
  this.staticProps = {};
};

VisualMap.getInstance = (function () {
  let instance;
  return function () {
    instance = instance ? instance : new VisualMap();
    return instance;
  };
})();

export const visualMaps = VisualMap.getInstance();
